package m

import (
	"GameServer/Game/cache"
	"GameServer/Game/dbmodule"
	"GameServer/Game/errors"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"
)

// 用户收集道具
type UserColloctProp struct {
	BaseM
	Uid bson.ObjectId `bson:"_id" json:"_id"` // 用户uid

	ActivId   int64 `bson:"activId" json:"activId"`     // 收集活动
	BeginTime int64 `bson:"beginTime" json:"beginTime"` // 活动开始时间
	EndTime   int64 `bson:"endTime" json:"endTime"`     // 活动结束时间

	Level    int64           `bson:"level" json:"level"`       // 当前等级
	MaxLevel int64           `bson:"maxLevel" json:"maxLevel"` // 最大等级
	MProp    map[int64]int64 `bson:"mProp" json:"mProp"`       // [道具id]道具数量 拥有道具
	State    int64           `bson:"state" json:"state"`       // 0.未完成 1.完成 2.已领取
	// 达成条件的道具
	MReachColloctProp map[int64]ReachColloctProp `bson:"mReachColloctProp" json:"mReachColloctProp"`
}

// 达成条件和奖励
type ReachColloctProp struct {
	MProp   map[int64]int64 `bson:"mProp" json:"mProp"`     // 达成条件道具数量
	LReward []BaseKV        `bson:"lReward" json:"lReward"` // 奖励
}

func NewUserColloctProp() cache.EntryI {
	return &UserColloctProp{
		MProp:             make(map[int64]int64),
		MReachColloctProp: make(map[int64]ReachColloctProp),
	}
}

// 保存信息
func (this *UserColloctProp) Save() (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("UserColloctProp", bson.M{"_id": this.Uid}, this)
	if err != nil {
		return err
	}
	return
}

func (this *UserColloctProp) Load(key interface{}) (err error) {
	switch key.(type) {
	case string:
		if key.(string) == "" {
			return errors.New("无效的key load, key empty")
		}
		this.Uid = bson.ObjectIdHex(key.(string))
	case bson.ObjectId:
		this.Uid = key.(bson.ObjectId)
	default:
		log.WithFields(log.Fields{
			"method": "UserChristmasTree_Load",
			"data":   key,
		}).Error("无效的key load")
		return errors.New("无效的key load")
	}
	return this.LoadData()
}

// 加载数据
func (this *UserColloctProp) LoadData() (err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("UserColloctProp", bson.M{"_id": this.Uid}, nil, &this)
	if err != nil {
		if err.Error() == "not found" {
			return nil
		}
		return
	}
	return
}

// 更新数据
func (this *UserColloctProp) Update(val *UserColloctProp) {
	Cache.Put("UserColloctProp", val.Uid.Hex(), val)
	val.UpdateData()
}

// 获取每日礼包信息
func GetUserColloctProp(uid string) *UserColloctProp {
	v, _ := Cache.Get("UserColloctProp", uid)
	return v.(*UserColloctProp)
}
